package com.example.bsy.pinluosong;

import android.content.Context;
import android.content.DialogInterface;

import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class MainActivity extends AppCompatActivity {
    /*UI声明*/
    Button[] btCard;
    Button btCreateServer;
    Button btJoinServer;
    TextView mainText;
    TextView q1;
    TextView q2;
    TextView q3;
    RadioButton rb1;
    RadioButton rb2;
    RadioButton rb3;
    View view;
    EditText et;
    LayoutInflater layoutInflater=null;
    AlertDialog dialog = null;
    /*全局变量声明*/
    static int state = 0;//0表示初始状态，1表示已创建服务器正在等待连接，2表示游戏已开始，3表示主机已锁定，4表示客户机已锁定，5表示分数开始统计
    //对于客户机来说，3表示客户机已锁定，5表示分数统计完成
    static int sortState = 0;
    boolean serverOrNot = false;
    boolean scored=false;
    ServerSocket serverSocket;
    Socket socket = null;
    BufferedReader bufferedReader = null;
    PrintWriter printWriter = null;
    final String[] ip = {null};
    PinLuoSong pls = null;
    Card[] mycards = null;
    Card[] yourcards = null;
    Card[] yourFirst = null;
    Card[] yourSecond = null;
    Card[] yourThird = null;
    int myScore;
    int myScore1;
    int myScore2;
    int myScore3;
    int yourScore;
    int yourScore1;
    int yourScore2;
    int yourScore3;
    int[] score;
    boolean isDialog;

    class ScoreThread extends Thread{//分数线程用于牌型判定，计分并显示
        @Override
        public void run(){
            while(state!=5){
                ;
            }
            if(serverOrNot==true) {//服务器要计分
                if (pls.numOfFirst == 0) {//双方甩牌
                    myScore = pls.jugde(mycards, 0);
                } else {
                    myScore1 = pls.jugde(pls.firstCards, 1);
                    myScore2 = pls.jugde(pls.secondCards, 2);
                    myScore3 = pls.jugde(pls.thirdCards, 2);
                }
                if (yourFirst == null) {
                    yourScore = pls.jugde(yourcards, 0);
                } else {
                    yourScore1 = pls.jugde(yourFirst, 1);
                    yourScore2 = pls.jugde(yourSecond, 2);
                    yourScore3 = pls.jugde(yourThird, 2);
                }
            }
            //显示
            score=pls.analyse(myScore,myScore1,myScore2,myScore3,yourScore,yourScore1,yourScore2,yourScore3);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mainText.setText("");
                    if(myScore!=0){
                        mainText.append("你甩牌了！牌型为："+pls.toString(myScore)+'\n');
                        mainText.append("得分为："+score[0]+'\n');
                        mainText.append("你的牌是：");
                        for(int i=0;i<13;i++){
                            mainText.append(pls.myCards[i].toString()+' ');
                        }
                        mainText.append("\n\n");
                    }else {
                        mainText.append("你的头道牌型是："+pls.toString(myScore1)+'\n');
                        mainText.append("得分为："+score[1]+'\n');
                        mainText.append("你的牌是：");
                        for(int i=0;i<3;i++){
                            mainText.append(pls.firstCards[i].toString()+' ');
                        }
                        mainText.append("\n");
                        mainText.append("你的第二道牌型是："+pls.toString(myScore2)+'\n');
                        mainText.append("得分为："+score[2]+'\n');
                        mainText.append("你的牌是：");
                        for(int i=0;i<5;i++){
                            mainText.append(pls.secondCards[i].toString()+' ');
                        }
                        mainText.append("\n");
                        mainText.append("你的第三道牌型是："+pls.toString(myScore3)+'\n');
                        mainText.append("得分为："+score[3]+'\n');
                        mainText.append("你的牌是：");
                        for(int i=0;i<5;i++){
                            mainText.append(pls.thirdCards[i].toString()+' ');
                        }
                        mainText.append("\n\n");
                    }

                    if(yourScore!=0){
                        mainText.append("对手甩牌了！牌型为："+pls.toString(yourScore)+'\n');
                        mainText.append("得分为："+score[4]+'\n');
                        mainText.append("对手的牌是：");
                        for(int i=0;i<13;i++){
                            mainText.append(yourcards[i].toString()+' ');
                        }
                        mainText.append("\n\n");
                    }else {
                        mainText.append("对手的头道牌型是："+pls.toString(yourScore1)+'\n');
                        mainText.append("得分为："+score[5]+'\n');
                        mainText.append("对手的牌是：");
                        for(int i=0;i<3;i++){
                            mainText.append(yourFirst[i].toString()+' ');
                        }
                        mainText.append("\n");
                        mainText.append("对手的第二道牌型是："+pls.toString(yourScore2)+'\n');
                        mainText.append("得分为："+score[6]+'\n');
                        mainText.append("对手的牌是：");
                        for(int i=0;i<5;i++){
                            mainText.append(yourSecond[i].toString()+' ');
                        }
                        mainText.append("\n");
                        mainText.append("对手的第三道牌型是："+pls.toString(yourScore3)+'\n');
                        mainText.append("得分为："+score[7]+'\n');
                        mainText.append("对手的牌是：");
                        for(int i=0;i<5;i++){
                            mainText.append(yourThird[i].toString()+' ');
                        }
                        mainText.append("\n\n");
                    }

                    mainText.append("你的得分："+(score[0]+score[1]+score[2]+score[3])+'\n');
                    mainText.append("对手得分："+(score[4]+score[5]+score[6]+score[7])+'\n');
                }
            });

            scored=true;
        }
    }


    class CreateServerButtonListener implements View.OnClickListener {//创建服务器线程用于创建服务器、发牌、接受客户机消息、发送结果
        class ServerThread extends Thread {

            public void run() {
                try {
                    //获取本机IP地址
                    state=1;
                    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    int ip = wifiInfo.getIpAddress();
                    DhcpInfo info = wifiManager.getDhcpInfo();

                    int myadd= info.serverAddress;
                    String hostadd=((myadd & 0xff) + "." + (myadd >> 8 & 0xff) + "."
                            + (myadd >> 16 & 0xff) + "." + (myadd >> 24 & 0xff));
                    Log.i("host",hostadd);

                    final String ipAddress = ((ip & 0xff) + "." + (ip >> 8 & 0xff) + "."
                            + (ip >> 16 & 0xff) + "." + (ip >> 24 & 0xff));

                    /*

                    Log.i("server",serverSocket.getInetAddress().toString());
                    */
                    if(ip==0){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,"请连接wifi！",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else {
                        serverSocket = new ServerSocket(8888);
                        //打印连接信息
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mainText.append("服务器已创建，IP地址为：\n" + ipAddress+"\n");
                            }
                        });
                        //阻塞，开始等待接入
                        socket = serverSocket.accept();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mainText.append("客户机已连接，游戏开始！\n");
                                // 设置创建服务器按钮可用;

                            }
                        });
                        pls = new PinLuoSong();
                        serverOrNot = true;
                        mycards = pls.getMyCards();
                        yourcards = pls.getYourCards();//发牌

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < 13; i++) {
                                    btCard[i].setTextColor(mycards[i].getColor());
                                    btCard[i].setText(mycards[i].toString());
                                    btCreateServer.setText("提交并锁定");
                                    btJoinServer.setText("排序");
                                }
                            }
                        });//改变UI
                        state = 2;
                        String command = null;
                        if (socket != null) {
                            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            printWriter = new PrintWriter(socket.getOutputStream());

                            printWriter.append("G");
                            for (int i = 0; i < 13; i++) {
                                printWriter.append(yourcards[i].toCommand());
                            }
                            printWriter.append('\n');
                            printWriter.flush();
                            //////发牌 通信协议

                            while ((command = bufferedReader.readLine()) != null) {//阻塞式
                                if (command.charAt(0) == 'L') {
                                    if (command.charAt(1) == 'S') {

                                    } else if (command.charAt(1) == 'N') {
                                        yourFirst = Card.fromCommand(command, 2, 7);
                                        yourSecond = Card.fromCommand(command, 8, 17);
                                        yourThird = Card.fromCommand(command, 18, 27);

                                    }
                                    Log.i("Client Card", command);
                                    if (state == 3) {
                                        state = 5;
                                    } else if (state == 2) {
                                        state = 4;
                                    }
                                    break;
                                }

                            }//收牌通信协议

                            while (state != 5) {
                                ;//4状态，客户机已锁定 主机尚未锁定，等到state改变后跳出。
                            }
                            if (state == 5) {
                                new ScoreThread().start();
                                while (!scored) {
                                    ;
                                }
                                Log.i("serverscore", myScore1 + "");
                                Log.i("serverscore", myScore2 + "");
                                Log.i("serverscore", myScore3 + "");
                                Log.i("serverscore", yourScore1 + "");
                                Log.i("serverscore", yourScore2 + "");
                                Log.i("serverscore", yourScore3 + "");
                                String buffer="";
                                buffer+='J';
                                if (pls.numOfFirst == 0 && yourFirst == null) {//双方甩牌
                                    buffer+='D';
                                    buffer+=((char) (myScore / 0x10000));
                                    buffer+=((char) (myScore % 0x10000));
                                    for (int i = 0; i < 13; i++) {
                                        buffer+=(mycards[i].toCommand());
                                    }
                                    buffer+=((char) (yourScore / 0x10000));
                                    buffer+=((char) (yourScore % 0x10000));
                                    //buffer+=('\n');
                                    //printWriter.append(buffer);
                                    //printWriter.flush();
                                } else if (pls.numOfFirst == 0 && yourFirst != null) {//主机甩牌
                                    buffer+=('S');
                                    buffer+=((char) (myScore / 0x10000));
                                    buffer+=((char) (myScore % 0x10000));
                                    for (int i = 0; i < 13; i++) {
                                        buffer+=(mycards[i].toCommand());
                                    }

                                    buffer+=((char) (yourScore1 / 0x10000));
                                    buffer+=((char) (yourScore1 % 0x10000));

                                    buffer+=((char) (yourScore2 / 0x10000));
                                    buffer+=((char) (yourScore2 % 0x10000));

                                    buffer+=((char) (yourScore3 / 0x10000));
                                    buffer+=((char) (yourScore3 % 0x10000));

                                    //buffer+=('\n');
                                    //printWriter.append(buffer);
                                    //printWriter.flush();
                                } else if (pls.numOfFirst != 0 && yourFirst == null) {//客户机甩牌
                                    buffer+=('C');
                                    buffer+=((char) (myScore1 / 0x10000));
                                    buffer+=((char) (myScore1 % 0x10000));
                                    for (int i = 0; i < 3; i++) {
                                        buffer+=(pls.firstCards[i].toCommand());
                                    }

                                    buffer+=((char) (myScore2 / 0x10000));
                                    buffer+=((char) (myScore2 % 0x10000));
                                    for (int i = 0; i < 5; i++) {
                                        buffer+=(pls.secondCards[i].toCommand());
                                    }

                                    buffer+=((char) (myScore3 / 0x10000));
                                    buffer+=((char) (myScore3 % 0x10000));
                                    for (int i = 0; i < 5; i++) {
                                        buffer+=(pls.thirdCards[i].toCommand());
                                    }

                                    buffer+=((char) (yourScore / 0x10000));
                                    buffer+=((char) (yourScore % 0x10000));

                                    //buffer+=('\n');
                                    //printWriter.append(buffer);
                                    //printWriter.flush();
                                } else if (pls.numOfFirst != 0 && yourFirst != null) {//双方普通牌
                                    buffer+=('N');
                                    buffer+=((char) (myScore1 / 0x10000));
                                    buffer+=((char) (myScore1 % 0x10000));
                                    for (int i = 0; i < 3; i++) {
                                        buffer+=(pls.firstCards[i].toCommand());
                                    }

                                    buffer+=((char) (myScore2 / 0x10000));
                                    Log.i("MYSCORE",(int)((char) (myScore2 / 0x10000))+"");
                                    buffer+=((char) (myScore2 % 0x10000));
                                    Log.i("MYSCORE",(int)((char) (myScore2 % 0x10000))+"");
                                    Log.i("MYSCORE1",(int)buffer.charAt(11)+"S");
                                    for (int i = 0; i < 5; i++) {
                                        buffer+=(pls.secondCards[i].toCommand());
                                    }

                                    buffer+=((char) (myScore3 / 0x10000));
                                    buffer+=((char) (myScore3 % 0x10000));
                                    for (int i = 0; i < 5; i++) {
                                        buffer+=(pls.thirdCards[i].toCommand());
                                    }

                                    buffer+=((char) (yourScore1 / 0x10000));
                                    buffer+=((char) (yourScore1 % 0x10000));
                                    buffer+=((char) (yourScore2 / 0x10000));
                                    Log.i("YOURSCORE",(int)((char) (yourScore2 / 0x10000))+"");
                                    buffer+=((char) (yourScore2 % 0x10000));
                                    Log.i("YOURSCORE",(int)((char) (yourScore2 % 0x10000))+"");
                                    Log.i("MYSCORE1",(int)buffer.charAt(11)+"S");
                                    buffer+=((char) (yourScore3 / 0x10000));
                                    buffer+=((char) (yourScore3 % 0x10000));
                                    //printWriter.append(' ');

                                    //buffer+=('\n');
                                    //printWriter.append(buffer);
                                    //printWriter.flush();
                                }
                                String test="";
                                for(int i=0;i<buffer.length();i++){
                                    test+=(int)buffer.charAt(i)+" ";
                                }
                                Log.i("allstring",test);
                                for(int i=0;i<buffer.length();i++){
                                    if((buffer.charAt(i)&0xD000)==0xD000) {
                                        buffer = buffer.replace(buffer.charAt(i), (char) (buffer.charAt(i) + 0x2000));
                                    }
                                }
                                buffer=buffer.replace('\n',(char)0xff00);
                                buffer=buffer.replace('\r',(char)0xffee);

                                Log.i("after",buffer);
                                test="";
                                for(int i=0;i<buffer.length();i++){
                                    test+=(int)buffer.charAt(i)+" ";
                                }
                                Log.i("allstring",test);
                                    //}
                                //}
                                buffer+='\n';
                                printWriter.append(buffer);
                                printWriter.flush();
                                //发送结果

                            }

                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

        @Override
        public void onClick(View v) {
            int int1=1104242;
            Log.i("test",(int)((char)(int1/0x10000))+"");
            Log.i("test",(int)((char)(int1%0x10000))+"");

            if (state == 0) {
                serverOrNot = true;
                ServerThread serverThread = new ServerThread();
                serverThread.start();
                //设置按钮不可用;
            }
            if (state == 2 || state == 3 || state == 4) {
                if ((pls.numOfFirst == 0 && pls.numOfSecond == 0 && pls.numOfThird == 0) && pls.jugde(mycards,0)==0) {
                    Toast.makeText(MainActivity.this,"此手牌无法甩牌！",Toast.LENGTH_SHORT).show();
                    //弹不能甩牌对话框
                }else if(pls.numOfFirst != 3 && pls.numOfSecond != 5 && pls.numOfThird != 5
                        &&(!(pls.numOfFirst == 0 && pls.numOfSecond == 0 && pls.numOfThird == 0))){
                    Toast.makeText(MainActivity.this,"牌还没摆放齐！",Toast.LENGTH_SHORT).show();
                    //弹牌没放齐对话框
                }else if(pls.jugde(pls.firstCards,1)>pls.jugde(pls.secondCards,2)){
                    Toast.makeText(MainActivity.this,"头道牌大于第二道！",Toast.LENGTH_SHORT).show();
                    //弹头道大于第二道对话框
                }else if(pls.jugde(pls.secondCards,2)>pls.jugde(pls.thirdCards,2)){
                    Toast.makeText(MainActivity.this,"第二道牌大于第三道！",Toast.LENGTH_SHORT).show();
                    //弹第二道大于第三道对话框
                }else if(pls.jugde(pls.firstCards,1)>pls.jugde(pls.thirdCards,2)){
                    Toast.makeText(MainActivity.this,"头道牌大于第三道！",Toast.LENGTH_SHORT).show();
                    //弹头道大于第三道对话框
                }else {
                    if (serverOrNot == true) {
                        if (state == 4) {
                            state = 5;
                            new ScoreThread().start();
                        }
                        if (state == 2) {
                            state = 3;
                        }
                    } else {//对于客户机来说，需要实现提交的功能
                        state = 5;
                    }
                    Toast.makeText(MainActivity.this,"提交成功！",Toast.LENGTH_SHORT).show();
                }

            }

        }
    }//创建服务器线程

    class JoinServerButtonListener implements View.OnClickListener {
        class ClientThread extends Thread {//客户端线程
            @Override
            public void run() {
                Log.i("Client", ip[0]);
                try {
                    Log.i("Client", ip[0]);

                    socket = new Socket(ip[0], 8888);
                    bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String br=null;
                    if ((br=bufferedReader.readLine())==null){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this,"加入服务器失败！",Toast.LENGTH_SHORT).show();
                            }
                        });
                        socket.close();
                    }else {
                        state = 2;
                        serverOrNot = false;
                        pls = new PinLuoSong();

                        mycards = Card.fromCommand(br, 1, 26);
                        pls.myCards = mycards;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mainText.append("已连接到服务器，游戏开始！\n");
                                for (int i = 0; i < 13; i++) {
                                    btCard[i].setTextColor(mycards[i].getColor());
                                    btCard[i].setText(mycards[i].toString());
                                    btCreateServer.setText("提交并锁定");
                                    btJoinServer.setText("排序");
                                }
                            }
                        });
                        //接收发牌

                        while (state != 5) {
                            ;
                        }
                        printWriter = new PrintWriter(socket.getOutputStream());
                        printWriter.append('L');
                        Log.i("Client Card", pls.numOfFirst + "");
                        if (pls.numOfFirst == 0) {
                            printWriter.append('S');//甩牌
                            printWriter.append('\n');
                            printWriter.flush();
                        } else {
                            printWriter.append('N');//普通牌
                            for (int i = 0; i < 3; i++) {
                                printWriter.append(pls.firstCards[i].toCommand());
                            }
                            for (int i = 0; i < 5; i++) {
                                printWriter.append(pls.secondCards[i].toCommand());
                            }
                            for (int i = 0; i < 5; i++) {
                                printWriter.append(pls.thirdCards[i].toCommand());
                            }
                            printWriter.append('\n');
                            printWriter.flush();
                        }//发送牌

                        String s = bufferedReader.readLine();
                        Log.i("string", s + "Andlength=" + s.length());
                        while (s.length() != 41) {
                            s += '\n';
                            Log.i("string", s + "Andlength=" + s.length());
                            if (s.length() != 41) s += bufferedReader.readLine();
                            Log.i("string", s + "Andlength=" + s.length());
                        }
                        String test="";
                        for(int i=0;i<s.length();i++){
                            test+=(int)s.charAt(i)+" ";
                        }
                        Log.i("allstring",test);
                        s=s.replace((char)0xffee,'\r');
                        s=s.replace((char)0xff00,'\n');
                        for(int i=0;i<s.length();i++){
                            if((s.charAt(i)&0xF000)==0xF000){
                                s=s.replace(s.charAt(i),(char)(s.charAt(i)-0x2000));
                            }

                        }
                        Log.i("after", s + "Andlength=" + s.length());
                        test="";
                        for(int i=0;i<s.length();i++){
                            test+=(int)s.charAt(i)+" ";
                        }
                        Log.i("allstring",test);
                        if (s.charAt(0) == 'J') {//JDysspspspsp...ms\n
                            if (s.charAt(1) == 'D') {
                                yourScore = (int) s.charAt(2) * 0x10000 + (int) s.charAt(3);
                                yourcards = Card.fromCommand(s, 4, 29);
                                myScore = (int) s.charAt(30) * 0x10000 + (int) s.charAt(31);
                            } else if (s.charAt(1) == 'S') {
                                yourScore = (int) s.charAt(2) * 0x10000 + (int) s.charAt(3);
                                yourcards = Card.fromCommand(s, 4, 29);
                                myScore1 = (int) s.charAt(30) * 0x10000 + (int) s.charAt(31);
                                myScore2 = (int) s.charAt(32) * 0x10000 + (int) s.charAt(33);
                                myScore3 = (int) s.charAt(34) * 0x10000 + (int) s.charAt(35);
                            } else if (s.charAt(1) == 'C') {
                                yourScore1 = (int) s.charAt(2) * 0x10000 + (int) s.charAt(3);
                                yourFirst = Card.fromCommand(s, 4, 9);
                                yourScore2 = (int) s.charAt(10) * 0x10000 + (int) s.charAt(11);
                                yourSecond = Card.fromCommand(s, 12, 21);
                                yourScore3 = (int) s.charAt(22) * 0x10000 + (int) s.charAt(23);
                                yourThird = Card.fromCommand(s, 24, 33);
                                myScore = (int) s.charAt(34) * 0x10000 + (int) s.charAt(35);
                            } else if (s.charAt(1) == 'N') {
                                yourScore1 = (int) s.charAt(2) * 0x10000 + (int) s.charAt(3);
                                yourFirst = Card.fromCommand(s, 4, 9);
                                yourScore2 = (int) s.charAt(10) * 0x10000 + (int) s.charAt(11);
                                Log.i("YOURSCORE",(int)s.charAt(10)+"");
                                Log.i("YOURSCORE",(int)s.charAt(11)+"");
                                yourSecond = Card.fromCommand(s, 12, 21);
                                yourScore3 = (int) s.charAt(22) * 0x10000 + (int) s.charAt(23);
                                yourThird = Card.fromCommand(s, 24, 33);
                                myScore1 = (int) s.charAt(34) * 0x10000 + (int) s.charAt(35);
                                myScore2 = (int) s.charAt(36) * 0x10000 + (int) s.charAt(37);
                                Log.i("YOURSCORE",(int)s.charAt(36)+"");
                                Log.i("YOURSCORE",(int)s.charAt(37)+"");
                                myScore3 = (int) s.charAt(38) * 0x10000 + (int) s.charAt(39);
                            }
                        }
                        Log.i("score", myScore1 + "");
                        Log.i("score", myScore2 + "");
                        Log.i("score", myScore3 + "");
                        Log.i("score", yourScore1 + "");
                        Log.i("score", yourScore2 + "");
                        Log.i("score", yourScore3 + ""+(int)'\r'+(int)'\n');

                        new ScoreThread().start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onClick(View v) {

            if (state == 0) {

                final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("输入服务器IP地址：");
                builder.setView(view);//加载view布局里的控件，如果写成R.layout.dialog就是两套控件了
                builder.setCancelable(false);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        ip[0] = et.getText().toString();
                        Log.i("Client", ip[0]);
                        ClientThread clientThread = new ClientThread();
                        clientThread.start();
                        isDialog=true;
                    }
                });

                if(!isDialog)dialog = builder.create();
                dialog.show();


            }
            if (state == 2 || (serverOrNot && state == 4) || (!serverOrNot && state == 3)) {
                //实现排序功能;
                if (sortState <= 0) {
                    pls.sortStraight(mycards, true);
                    sortState = 1;
                } else {
                    pls.sortFlush(mycards, true);
                    sortState = 0;
                }

                for (int i = 0; i < 13; i++) {
                    if (pls.myCards[i].used) {
                        btCard[i].setTextColor(mycards[i].getColor());
                        btCard[i].setText("√" + mycards[i].toString());

                    } else {
                        btCard[i].setTextColor(mycards[i].getColor());
                        btCard[i].setText(mycards[i].toString());

                    }
                }
            }

        }
    }//加入服务器线程

    class CardButtonListener implements View.OnClickListener {
        int id;

        CardButtonListener(int i) {
            super();
            id = i;
        }

        @Override
        public void onClick(View v) {
            if (state == 2 || (serverOrNot && state == 4) || (!serverOrNot && state == 3)) {//state暂且为0
                String text = (String) btCard[id].getText();
                String textBox = "";
                if (text.charAt(0) == '√') {
                    btCard[id].setText(text.substring(1, text.length()));
                    mycards[id].used = false;
                    pls.deleteCards(id);

                    for (int i = 0; i < pls.numOfFirst; i++) {
                        textBox += pls.firstCards[i].toString() + ",";
                    }
                    if (textBox == "") {
                        q1.setText("头道");
                    } else {
                        q1.setText(textBox);
                    }
                    textBox = "";
                    for (int i = 0; i < pls.numOfSecond; i++) {
                        textBox += pls.secondCards[i].toString() + ",";
                    }
                    if (textBox == "") {
                        q2.setText("第二道");
                    } else {
                        q2.setText(textBox);
                    }
                    textBox = "";
                    for (int i = 0; i < pls.numOfThird; i++) {
                        textBox += pls.thirdCards[i].toString() + ",";
                    }
                    if (textBox == "") {
                        q3.setText("第三道");
                    } else {
                        q3.setText(textBox);
                    }
                    textBox = "";
                } else {
                    if (rb1.isChecked()) {
                        if (pls.addFirstCards(id)) {
                            mycards[id].used = true;
                            btCard[id].setText("√" + text);
                        }
                        for (int i = 0; i < pls.numOfFirst; i++) {
                            textBox += pls.firstCards[i].toString() + ",";
                        }
                        q1.setText(textBox);
                        textBox = "";
                    } else if (rb2.isChecked()) {
                        if (pls.addSecondCards(id)) {
                            mycards[id].used = true;
                            btCard[id].setText("√" + text);
                        }
                        for (int i = 0; i < pls.numOfSecond; i++) {
                            textBox += pls.secondCards[i].toString() + ",";
                        }
                        q2.setText(textBox);
                        textBox = "";
                    } else if (rb3.isChecked()) {
                        if (pls.addThirdCards(id)) {
                            mycards[id].used = true;
                            btCard[id].setText("√" + text);
                        }
                        for (int i = 0; i < pls.numOfThird; i++) {
                            textBox += pls.thirdCards[i].toString() + ",";
                        }
                        q3.setText(textBox);
                        textBox = "";
                    }


                }


            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btCard = new Button[13];
        btCard[0] = (Button) findViewById(R.id.button);
        btCard[1] = (Button) findViewById(R.id.button2);
        btCard[2] = (Button) findViewById(R.id.button3);
        btCard[3] = (Button) findViewById(R.id.button4);
        btCard[4] = (Button) findViewById(R.id.button5);
        btCard[5] = (Button) findViewById(R.id.button6);
        btCard[6] = (Button) findViewById(R.id.button7);
        btCard[7] = (Button) findViewById(R.id.button8);
        btCard[8] = (Button) findViewById(R.id.button9);
        btCard[9] = (Button) findViewById(R.id.button10);
        btCard[10] = (Button) findViewById(R.id.button11);
        btCard[11] = (Button) findViewById(R.id.button12);
        btCard[12]
                = (Button) findViewById(R.id.button13);
        btCreateServer = (Button) findViewById(R.id.button15);
        btJoinServer = (Button) findViewById(R.id.button14);
        mainText = (TextView) findViewById(R.id.textView);
        q1 = (TextView) findViewById(R.id.textView2);
        q2 = (TextView) findViewById(R.id.textView3);
        q3 = (TextView) findViewById(R.id.textView4);
        rb1 = (RadioButton) findViewById(R.id.radioButton);
        rb2 = (RadioButton) findViewById(R.id.radioButton2);
        rb3 = (RadioButton) findViewById(R.id.radioButton3);
        layoutInflater = LayoutInflater.from(MainActivity.this);
        view = layoutInflater.inflate(R.layout.dialog, null);//加载布局
        et = (EditText) view.findViewById(R.id.editText);//此处只能这样写，因为EditText在dialog里，必须从dialog的view里获取
        et.setText("192.168.");
        //LinearLayout layout=new LinearLayout(view);
        btCreateServer.setOnClickListener(new CreateServerButtonListener());
        btJoinServer.setOnClickListener(new JoinServerButtonListener());
        for (int i = 0; i < 13; i++) {
            btCard[i].setOnClickListener(new CardButtonListener(i));
        }



    }

    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK){
            try {
                serverSocket.close();
                if(socket!=null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            finish();
            System.exit(0);
        }
        return true;
    }
}

